<?php
/**
 * @ClassName: Contacts
 * @Description: TODO
 * @author: gydtrade
 * @Date: 2025-11-20 13:06
 * @Version: V1.0.0
 */

namespace app\admin\controller\customer;

use app\common\logic\ContactsLogic;
use app\common\model;
use think\Controller;
use tpext\builder\traits\HasBuilder;

class Contacts extends Controller
{
    use HasBuilder;

    protected $dataModel;

    protected function initialize()
    {
        parent::initialize();

        $this->dataModel = new model\CustomerContacts();
        $this->pageTitle = '客户联系人管理';
        $this->pagesize = 10;

        $this->indexWith = ['customer', 'member'];
    }

    /**
     * 构建搜索
     * @return void
     */
    protected function buildSearch()
    {
        $search = $this->search;

        $search->select('customer_id', '客户')->dataUrl(url('/admin/customer.customer/selectPage'));
        $search->text('name', '姓名');
        $search->text('mobile', '联系电话');
        $search->text('keyword', '关键词');
        $search->select('member_id', '会员')->dataUrl(url('/admin/member/selectPage'));
    }

    /**
     * 构建查询条件
     * @return array
     */
    protected function filterWhere()
    {
        $searchData = request()->isGet() ? request()->param() : request()->post();

        $where = [];
        if (!empty($searchData['customer_id'])) {
            $where[] = ['customer_id', 'eq', $searchData['customer_id']];
        }
        if (!empty($searchData['name'])) {
            $where[] = ['name', 'like', '%' . $searchData['name'] . '%'];
        }
        if (!empty($searchData['mobile'])) {
            $where[] = ['mobile', 'like', '%' . $searchData['mobile'] . '%'];
        }
        if (!empty($searchData['keyword'])) {
            $where[] = ['name|mobile|subname|role|post|email', 'like', '%' . $searchData['keyword'] . '%'];
        }
        if (!empty($searchData['member_id'])) {
            $where[] = ['member_id', 'eq', $searchData['member_id']];
        }

        return $where;
    }

    /**
     * 构建表格
     * @param $data
     * @return void
     */
    protected function buildTable(&$data = [])
    {
        $table = $this->table;

        $table->show('id', 'ID');
        $table->match('customer_id', '客户')->to('{val}#{customer.customer_name}');
        $table->match('member_id', '会员')->to('{val}#{member.nickname}');
        $table->show('name', '姓名');
        $table->show('mobile', '手机号');
        $table->match('is_major', '是否主要联系人')->options([0 => '否', 1 => '是'])->mapClassGroup([[0, 'info'], [1, 'success']]);
        /*$table->show('subname', '简称或尊称');
        $table->show('role', '角色');
        $table->show('post', '职务');
        $table->show('email', '邮箱');*/
        $table->show('create_time', '添加时间');
        $table->show('update_time', '更新时间');


        $table->sortable('id, create_time, update_time');

        $table->getToolbar()
            ->btnAdd()
            ->btnRefresh();

        $table->getActionbar()
            ->btnView()
            ->btnEdit();
    }

    /**
     * 构建表单
     * @param $isEdit
     * @param $data
     * @return void
     */
    protected function buildForm($isEdit, &$data = [])
    {
        $form = $this->form;

        $form->hidden('id');

        $form->select('customer_id', '客户')->dataUrl(url('/admin/customer.customer/selectPage'))->required();
        $form->select('member_id', '会员')->dataUrl(url('/admin/member/selectPage'));
        $form->text('name', '姓名')->required();
        $form->text('subname', '简称或尊称');
        $form->text('mobile', '手机号')->required();
        $form->switchBtn('is_major', '是否主要联系人')->default(0)->required();
        $form->text('role', '角色');
        $form->text('post', '职务');
        $form->text('email', '邮箱');

        if ($isEdit) {
            $form->show('create_time', '添加时间');
            $form->show('update_time', '更新时间');
        }
    }

    /**
     * 保存
     * @param $id
     * @return \think\response\Json|\tpext\think\View
     */
    private function save($id = 0)
    {
        $data = request()->post();
        $result = $this->validate($data, []);

        if (!$result) {
            $this->error($result);
        }

        //判断会员是否绑定过
        $bind_member = (new ContactsLogic())->isBindMember($data['member_id'], $id);
        if ($bind_member) {
            $this->error('该会员已被绑定过，请勿重复绑定');
        }
        if (intval($data['is_major']) === 1) {
            //主要联系人只能有一个
            $res = model\CustomerContacts::where('customer_id', $data['customer_id'])->update(['is_major' => 0, 'update_time' => date('Y-m-d H:i:s')]);

            //更新客户表主要联系人
            $up_data = [
                'fullname' => $data['name'],
                'mobile' => $data['mobile'],
                'update_time' => date('Y-m-d H:i:s')
            ];
            $res1 = model\Customer::where('id', $data['customer_id'])->update($up_data);
        } else {
            $count = model\CustomerContacts::where('customer_id', $data['customer_id'])->where('is_major', 1)->count();
            if ($count == 0) {
                $this->error('必须要有一个主要联系人');
            }
        }

        return $this->doSave($data, $id);
    }
}